package com.vip.base.controller;

import com.vip.base.service.ISysDictService;
import com.vip.common.annotation.LogCollection;
import com.vip.common.constant.UrlConsts;
import com.vip.common.response.ErrorCode;
import com.vip.common.response.RestResponse;
import com.vip.common.response.RestResponses;
import com.vip.database.dto.dict.AddDictDTO;
import com.vip.database.dto.dict.GetDictDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 字典管理
 *
 * @author wgb
 * @date 2020/1/18 15:04
 */
@RestController
@RequestMapping(value = UrlConsts.API + "/dict")
public class SysDictController {
    @Autowired
    private ISysDictService dictService;

    /**
     * 分页获取字典列表数据
     *
     * @param pageNo   当前页
     * @param pageSize 当前页大小
     * @return 当前页列表数据
     */
    @PreAuthorize("hasAuthority('perm:select')")
    @GetMapping(value = "/list")
    public RestResponse<List<GetDictDTO>> getDictList(@RequestParam Integer pageNo, @RequestParam Integer pageSize) {
        return RestResponses.newResponseFromResult(dictService.getDictList(pageNo, pageSize));
    }

    /**
     * 根据父Code获取其子字典数据
     *
     * @return
     */
    @GetMapping(value = "/child/list/{code}")
    public RestResponse<List<GetDictDTO>> getDictChildList(@PathVariable String code) {
        return RestResponses.newResponseFromResult(dictService.getDictChildList(code));
    }

    /**
     * 添加新字典
     *
     * @param dto
     * @param bindingResult
     * @return
     */
    @LogCollection
    @PostMapping
    public RestResponse<String> addNewDict(@RequestBody @Valid AddDictDTO dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return RestResponses.newFailResponse(ErrorCode.INVALID_PARAMETER, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return RestResponses.newResponseFromResult(dictService.addNewDict(dto));
    }

    /**
     * 更新字典信息
     *
     * @param dictDto
     * @param bindingResult
     * @return
     */
    @LogCollection
    @PutMapping
    public RestResponse<String> updateDict(@RequestBody @Valid AddDictDTO dictDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return RestResponses.newFailResponse(ErrorCode.INVALID_PARAMETER, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return RestResponses.newResponseFromResult(dictService.updateDict(dictDto));
    }
}
